const db = require('../db')
const _ = require('lodash')
const utils = require('utility')
const config = require('config')
const DB_NAME = 'Admin'

const encodePassword = (password) => {
  return  utils.md5(password + config.sault.op)
}

const remove = async (id) => {
  const result = await db(DB_NAME)
    .update({
      status: 1,
      updateTime: new Date()
    })
    .where('id', '=', id)
  return true
}

const createUser = async ({username, password, role}) => {
  const results = await db(DB_NAME).returning('id').insert({
    username: username,
    password: encodePassword(password),
    role: role
  })
  return results[0]
}

const findById = async (id) => {
  const users = await db(DB_NAME).where('id', '=', id).select()
  return users[0]
}

const findByName = async (username) => {
  const users = await db(DB_NAME).where('username', '=', username).select()
  return users[0]
}

const findAll = async () => {
  const users = await db(DB_NAME).where('status', '=', '0').select()  
  return users.map((user) => {
    return _.omit(user, ['password', 'token'])
  })
}

const updateUser = async (id, info) => {
  const user = {};
  ['role'].forEach((key) => {
    user[key] = info[key]
  })
  const result = await db(DB_NAME)
  .where('id', '=', id)
  .update(user)
  return result
}

const modifyPassword = async (u, origin, password, force) => {
  const user = await findById(u.id)
  if (user.password == encodePassword(origin) || force) {
    const result = await db(DB_NAME).update({
      password: encodePassword(password)
    }).where('id', '=', user.id)
    return true
  } else {
    throw new Error('原密码不匹配')
  }
}

module.exports = {
  createUser,
  updateUser,
  remove,
  findByName,
  findById,
  findAll,
  modifyPassword
}